import { withInstall } from "./vue";
const THEMEKEY = "theme-mode";
const toggle = () => {
  const isDark = localStorage.getItem(THEMEKEY) == "dark";
  const root = document.documentElement;
  if (isDark) {
    root.setAttribute(THEMEKEY, "light");
    localStorage.setItem(THEMEKEY, "light");
  } else {
    root.setAttribute(THEMEKEY, "dark");
    localStorage.setItem(THEMEKEY, "dark");
  }
  return !isDark;
};

const Theme = {
  name: "Theme",
  setThemeMode(event, callback) {
    const x = event.clientX;
    const y = event.clientY;
    const endRadius = Math.hypot(
      Math.max(x, window.innerWidth - x),
      Math.max(y, window.innerHeight - y)
    );
    const root = document.documentElement;
    let isDark = localStorage.getItem("theme") == "dark";

    if (typeof document.startViewTransition === "function") {
      document
        .startViewTransition(() => {
          isDark = toggle();
          callback?.(isDark);
        })
        .ready.then(() => {
          const clippath = [
            `circle(0px at ${x}px ${y}px)`,
            `circle(${endRadius}px at ${x}px ${y}px)`,
          ];
          const ani = root.animate(
            {
              clipPath: !isDark ? clippath.reverse() : clippath,
            },
            {
              duration: 500,
              easing: "ease-in-out",
              pseudoElement: !isDark
                ? "::view-transition-old(root)"
                : "::view-transition-new(root)",
            }
          )
          ani.onfinish = () => {
            // root.style.clipPath = "none";
          }
        });
    } else {
      isDark = toggle();
      callback?.(isDark);
    }
  },
};

export default withInstall(Theme);
